package com.zhq.apputil.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;

import com.zhq.apputil.R;
import com.zhq.apputil.utils.LogUtil;
import com.zhq.apputil.utils.ScreenUtils;
import com.zhq.apputil.widget.bean.BadgeBean;
import com.zhq.apputil.widget.bean.IConRedDotBean;

import java.util.ArrayList;

/**
 * @author zhq
 * @Description: 底部导航栏
 */
public class NavigationMenuBar extends LinearLayout implements View.OnClickListener {
    public static final int LEFT = 0, TOP = 1, RIGHT = 2, BOTTOM = 3;
    private int bottomCount = 4;//底部导航栏默认的数量值
    private int textNormal;
    private int textSelect;
    private CharSequence[] mLabels;
    private int lineColor, bgColor, itemBackground;
    private int buttonSelectNormalColor = R.color.white;
    private int buttonSelectPressedColor =R.color.separation;
    private int[] colors = new int[2];
    private static final float[] floats = new float[]{0f, 1.0f};
    private int[] imageNormal;
    private int[] imagePressed;
    private int currentPosition = 0;
    private int location, paddingSize;
    private int imageWidth = ScreenUtils.dpToPx(getResources(), 25);
    private float mShadowRadius;
    private Paint mPaint;
    private int mViewHeight, mViewWidth;
    private IConRedDotBean iConRedDotBean;
    private OnTabSelectedListener onTabSelectedListener;
    private ArrayList<IconTextView> mBottomNavigationItems = new ArrayList<>();

    public NavigationMenuBar(Context context) {
        super(context);
    }

    public NavigationMenuBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        setOrientation(LinearLayout.HORIZONTAL);//设置位置
        setPadding(0, ScreenUtils.dpToPx(getResources(), 1), 0, 0);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NavigationMenuBar);
        textNormal = typedArray.getColor(R.styleable.NavigationMenuBar_text_color_normal, Color.parseColor("#242D34"));
        textSelect = typedArray.getColor(R.styleable.NavigationMenuBar_text_color_pressed, Color.parseColor("#242D34"));
        lineColor = typedArray.getColor(R.styleable.NavigationMenuBar_shadow_line_color, Color.parseColor("#C9C9C9"));
        mShadowRadius = typedArray.getDimension(R.styleable.NavigationMenuBar_shadow_line_width, ScreenUtils.dpToPx(getResources(), 2));
        buttonSelectNormalColor = typedArray.getResourceId(R.styleable.NavigationMenuBar_button_select_color_normal, R.color.white);
        buttonSelectPressedColor = typedArray.getResourceId(R.styleable.NavigationMenuBar_button_select_color_pressed,  R.color.separation);
        bgColor = typedArray.getColor(R.styleable.NavigationMenuBar_background_color, Color.parseColor("#FFFFFF"));
        float fontSize = typedArray.getDimension(R.styleable.NavigationMenuBar_text_font_size, 16f);
        bottomCount = typedArray.getInteger(R.styleable.NavigationMenuBar_bottom_count, 4);
        // 读取布局中，各个tab使用的文字
        if (typedArray.hasValue(R.styleable.NavigationMenuBar_text_labels)) {
            mLabels = typedArray.getTextArray(R.styleable.NavigationMenuBar_text_labels);
        }
        setBackgroundColor(bgColor);
        typedArray.recycle();
        iConRedDotBean = new IConRedDotBean();
        for (int i = 0; i < bottomCount; i++) {
            IconTextView iconTextView = new IconTextView(context);
            iconTextView.setBackgroundDrawable(newSelector(context, buttonSelectNormalColor, buttonSelectPressedColor));
            iconTextView.setTag(i);
            iconTextView.setGravity(Gravity.CENTER);
            iconTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
            iconTextView.getPaint().setTextSize(fontSize);
            iconTextView.setTextColor(textNormal);
            if (mLabels != null && mLabels.length == bottomCount) {
                iconTextView.setText(mLabels[i]);
            }
            iconTextView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
            iconTextView.setOnClickListener(this);
            addView(iconTextView);
            mBottomNavigationItems.add(iconTextView);
        }
        mPaint = new Paint();
        mPaint.setColor(lineColor);                    //设置画笔颜色
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(mShadowRadius);              //设置线宽
        mPaint.setAntiAlias(true);
        colors = new int[]{lineColor, 0x00ffffff};
    }


    /**
     * 设置Selector。
     */
    private StateListDrawable newSelector(Context context, int idNormal, int idPressed) {
        StateListDrawable bg = new StateListDrawable();
        Drawable normal = idNormal == -1 ? null : context.getResources().getDrawable(idNormal);
        Drawable pressed = idPressed == -1 ? null : context.getResources().getDrawable(idPressed);
        // View.PRESSED_ENABLED_STATE_SET
        bg.addState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled}, pressed);
        // View.ENABLED_STATE_SET
        bg.addState(new int[]{android.R.attr.state_enabled}, normal);
        // View.EMPTY_STATE_SET
        bg.addState(new int[]{}, normal);
        return bg;
    }

    /**
     * @param bottomTextResource:所引用的未点击内容资源
     **/
    public NavigationMenuBar setBottomNameResource(CharSequence[] bottomTextResource) {
        mLabels = bottomTextResource;
        bottomCount = bottomTextResource.length;
        return this;
    }


    /**
     * @param imageNormalRes:所引用的未点击image资源
     * @param imagePressedRes：所引用的点击后image资源
     **/
    public NavigationMenuBar setImageResource(int[] imageNormalRes, int[] imagePressedRes) {
        imageNormal = imageNormalRes;
        imagePressed = imagePressedRes;
        return this;
    }


    /***
     * 设置图片尺寸大小
     * @param imageWidth
     * @return
     */
    public NavigationMenuBar setImageWidth(int imageWidth) {
        this.imageWidth = ScreenUtils.dpToPx(getResources(), imageWidth);
        return this;
    }

    /**
     * @param location:设置字体的位置
     * @param paddingSize：字体的位置偏移距离
     **/
    public NavigationMenuBar setFontPadding(int location, int paddingSize) {
        this.location = location;
        this.paddingSize = paddingSize;
        return this;
    }


    /**
     * @param badgeBean:设置是否显示消息红点
     **/
    public NavigationMenuBar setShowRedDot(BadgeBean badgeBean) {
        iConRedDotBean.setBadgeBean(badgeBean);
        return this;
    }

    /**
     * @param bgColor:设置底部导航背景色
     **/
    public NavigationMenuBar setBottomMenuBackgroundColor(int bgColor) {
        this.bgColor = bgColor;
        setBackgroundColor(bgColor);
        return this;
    }

    /***
     * 设置itemBar背景色
     * @param itemBackground
     * @return
     */
    public NavigationMenuBar setBottomMenuItemBackgroundDrawable(int itemBackground) {
        this.itemBackground = itemBackground;
        return this;
    }

    /**
     * @param position:默认第一个选中位置
     **/
    public NavigationMenuBar initToPosition(int position) {
        this.currentPosition = position;
        return this;
    }

    /**
     * 初始化
     * *
     */
    public void builder() {
        int padding = ScreenUtils.dpToPx(getResources(), paddingSize);
        if (bottomCount > 0 && imageNormal != null && imagePressed != null) {
            for (int i = 0; i < bottomCount; i++) {
                IconTextView iconTextView = mBottomNavigationItems.get(i);
                if (imageNormal.length != 0 && imagePressed.length != 0) {
                    iConRedDotBean.setNormalImageResources(imageNormal[i]);
                    iConRedDotBean.setPressedImageResources(imagePressed[i]);
                    iConRedDotBean.setNormalFont(textNormal);
                    iConRedDotBean.setPressedFont(textSelect);
                    iconTextView.setText(mLabels[i]);
                    iConRedDotBean.setSelectState(i == currentPosition);
                    iconTextView.setIconTop(iConRedDotBean, i, imageWidth);
                    if (itemBackground != 0) {
                        iconTextView.setBackgroundResource(itemBackground);
                    }
                }
                switch (location) {
                    case LEFT:
                        iconTextView.setPadding(padding, 0, 0, 0);
                        break;
                    case TOP:
                        iconTextView.setPadding(0, padding, 0, 0);
                        break;
                    case RIGHT:
                        iconTextView.setPadding(0, 0, padding, 0);
                        break;
                    case BOTTOM:
                        iconTextView.setPadding(0, 0, 0, padding);
                        break;
                }
            }
        }
    }


    /**
     * @param position:设置选中的位置
     **/
    private void setSelectPositionBottom(int position) {
        if (currentPosition < bottomCount) {
            if (imageNormal != null && imagePressed != null) {
                IconTextView selectTextView = mBottomNavigationItems.get(position);
                IconTextView unSelectTextView = mBottomNavigationItems.get(currentPosition);
                selectTextView.setIconTop(getIConRedDotBean(position, true), position, imageWidth);
                unSelectTextView.setIconTop(getIConRedDotBean(currentPosition, false), currentPosition, imageWidth);
            }
        }
    }


    private IConRedDotBean getIConRedDotBean(int position, boolean isSelect) {
        iConRedDotBean.setNormalImageResources(imageNormal[position]);
        iConRedDotBean.setPressedImageResources(imagePressed[position]);
        iConRedDotBean.setSelectState(isSelect);
        return iConRedDotBean;
    }


    /**
     * 刷新消息
     **/
    public void refreshRedDot() {
        if (mBottomNavigationItems != null && mBottomNavigationItems.size() > 0) {
            IconTextView iconTextView = mBottomNavigationItems.get(currentPosition);
            iconTextView.setIconTop(getIConRedDotBean(currentPosition, true), currentPosition, imageWidth);
        }
    }


    /**
     * @param position:发送选中方式
     **/
    public void sendNoticeListener(int position) {
        if (currentPosition != position) {
            setSelectPositionBottom(position);
            if (onTabSelectedListener != null) {
                onTabSelectedListener.onTabSelected(position, currentPosition);
                this.currentPosition = position;
            }
        }
    }


    @Override
    public void onClick(View v) {
        int tag = (int) v.getTag();//点击的item
        sendNoticeListener(tag);
    }


    public int getCurrentSelectedPosition() {
        return currentPosition;
    }

    /**
     * @param onTabSelectedListener：绑定事件
     **/
    public void setOnTabSelectedListener(OnTabSelectedListener onTabSelectedListener) {
        this.onTabSelectedListener = onTabSelectedListener;
    }

    /**
     * 底部导航监听器
     */
    public interface OnTabSelectedListener {
        /**
         * @param currentPosition：选中的当前位置
         * @param lastIndex:上次选中的位置
         **/
        void onTabSelected(int currentPosition, int lastIndex);
    }

    public void unBindListener() {
        onTabSelectedListener = null;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        float effect = mShadowRadius;
        int paddingTop = (int) effect;
        this.setPadding(0, paddingTop, 0, 0);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mViewHeight = h;
        mViewWidth = w;
        LogUtil.e("width", "" + mViewWidth);
    }

    /**
     * 绘制线条
     * getLeft:获取布局左边的x坐标
     * getRight:获取布局右边的x坐标
     * 线条左边和右边Y坐标为0，只限制当前布局
     * 如若是getTop:坐标相对于屏幕的高度-布局的高度
     **/
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.reset();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(mShadowRadius);              //设置线宽
        LogUtil.e("width", "" + getWidth());
        LinearGradient linearGradient = new LinearGradient(0, mShadowRadius, 0, 0, colors, floats, Shader.TileMode.CLAMP);
        mPaint.setShader(linearGradient);
        canvas.drawRect(new RectF(0, 0, mViewWidth == 0 ? getWidth() : mViewWidth, mShadowRadius), mPaint);
    }
}
